/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import DAO.LoginDAO;
import DAO.TimeDAO;
import DAO.TimeJogoDAO;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Login;
import model.Mensagem;
import model.Time;

/**
 *
 * @author Alberto
 */
public class Controller_Time extends HttpServlet {

    public void cadastrar(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Object> obj = new ArrayList<Object>();

        Time time = new Time();
        TimeDAO dao = new TimeDAO();
        Login login = new Login();
        LoginDAO loginDAO = new LoginDAO();
        Mensagem msg = new Mensagem();
        Gson objJson = new Gson();
        Login novoLogin = new Login();

        try {

            login.setUsuario(request.getParameter("email_responsavel"));
            login.setSenha(request.getParameter("senha"));
            int timesA;
            int timesB;
            int st;
            String teste;
            timesA = dao.contarTimesA();
            timesB = dao.contarTimesB();

            if (loginDAO.criar(login) == true) {
                System.out.println("Login criado!!!");
            } else {
                System.out.println("Erro ao criar o login.");
                throw new Exception("Houve um erro ao criar o login.");
            }
            novoLogin = loginDAO.login(login.getUsuario(), login.getSenha());
            if (novoLogin.getId() == 0) {
                throw new Exception("O login não foi cadastrado com sucesso.");

            } else {
                time.setNome_time(request.getParameter("nome_time"));
                time.setLogin(novoLogin);
                time.setCidade_time(request.getParameter("cidade"));
                time.setNome_responsavel(request.getParameter("nome_responsavel"));
                time.setCpf_responsavel(request.getParameter("cpf_responsavel"));
                time.setEmail_responsavel(request.getParameter("email_responsavel"));
                time.setTelefone_responsavel(request.getParameter("tel_responsavel"));
                time.setComentario(request.getParameter("comentario"));
                time.setCategoria(request.getParameter("categoria"));

                teste = request.getParameter("categoria");

                if ("A".equals(teste)) {
                    if (timesA < 18) {
                        time.setStatus(2);
                    } else {
                        time.setStatus(3);
                    }
                } else {
                    if (timesB < 18) {
                        time.setStatus(2);
                    } else {
                        time.setStatus(3);
                    }
                }

                dao.criar(time);
                msg.setMensagem("Cadastro efetuado com sucesso!!!");

                obj.add(msg);
                out.print(objJson.toJson(obj));

            }

        } catch (Exception e) {
            loginDAO.apagar(novoLogin.getId());

            System.out.println("Erro na servlet ao cadastrar o time" + e.getStackTrace());

        } finally {

        }

    }

        public void listar(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Time> obj = new ArrayList<Time>();

        Gson objJson = new Gson();

        try {
            TimeDAO timeDAO = new TimeDAO();

            obj = timeDAO.buscarTimes();

            out.print(objJson.toJson(obj));

        } catch (Exception e) {

            System.out.println("Erro na servlet ao listar os times" + e.getStackTrace());

        } finally {
            out.close();
        }

    }

    public void alterar(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Object> arrobj = new ArrayList<Object>();
        Gson objJson = new Gson();

        try {

            Time time = new Time();
            TimeDAO timeDAO = new TimeDAO();

            time.setId_time(Integer.parseInt(request.getParameter("id")));
            time.setNome_time(request.getParameter("nomeTime"));
            time.setCidade_time(request.getParameter("cidadeTime"));
            time.setNome_responsavel(request.getParameter("nomeResponsavel"));
            time.setCpf_responsavel(request.getParameter("cpfResponsavel"));
            time.setEmail_responsavel(request.getParameter("emailResponsavel"));
            time.setTelefone_responsavel(request.getParameter("telefoneResponsavel"));

            timeDAO.atualizar(time);

            out.print(objJson.toJson(arrobj));

        } catch (Exception e) {

            //perceba que a mensagem é gerada na controladora
            System.out.println("Erro ao alterar o time " + e.getMessage());

            out.print(objJson.toJson(arrobj));

        } finally {
            out.close();
        }

    }

    public void apagar(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        PrintWriter out = response.getWriter();
        Gson objJson = new Gson();
        TimeDAO dao = new TimeDAO();

        ArrayList<Object> arrobj = new ArrayList<Object>();

        try {

            dao.apagar(Integer.parseInt(request.getParameter("id")));
            out.print(objJson.toJson(arrobj));

        } catch (Exception e) {
            System.out.println("Erro ao buscar por ID o login");
        } finally {
            out.close();
        }

    }

    public void ativo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        PrintWriter out = response.getWriter();
        Gson objJson = new Gson();
        TimeDAO dao = new TimeDAO();

        ArrayList<Object> arrobj = new ArrayList<Object>();

        try {

            dao.marcarAtivo(Integer.parseInt(request.getParameter("id")));
            out.print(objJson.toJson(arrobj));

        } catch (Exception e) {
            System.out.println("Erro ao finalizar a compra");
        } finally {
            out.close();
        }

    }

    public void inativo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        PrintWriter out = response.getWriter();
        Gson objJson = new Gson();
        TimeDAO dao = new TimeDAO();

        ArrayList<Object> arrobj = new ArrayList<Object>();

        try {

            dao.marcarInativo(Integer.parseInt(request.getParameter("id")));
            out.print(objJson.toJson(arrobj));

        } catch (Exception e) {
            System.out.println("Erro ao finalizar a compra");
        } finally {
            out.close();
        }

    }

    public void sortearHA(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Time> obj = new ArrayList<Time>();

        Gson objJson = new Gson();

        try {
            TimeDAO timeDAO = new TimeDAO();

            obj = timeDAO.sortearCabecaA();

            out.print(objJson.toJson(obj));

        } catch (Exception e) {

            System.out.println("Erro na servlet ao listar os times" + e.getStackTrace());

        } finally {
            out.close();
        }

    }

    public void sortearBA(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Time> obj = new ArrayList<Time>();

        Gson objJson = new Gson();

        try {
            TimeDAO timeDAO = new TimeDAO();

            obj = timeDAO.sortearCorpoA();

            out.print(objJson.toJson(obj));

        } catch (Exception e) {

            System.out.println("Erro na servlet ao listar os times" + e.getStackTrace());

        } finally {
            out.close();
        }

    }

    public void sortearHB(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Time> obj = new ArrayList<Time>();

        Gson objJson = new Gson();

        try {
            TimeDAO timeDAO = new TimeDAO();

            obj = timeDAO.sortearCabecaB();

            out.print(objJson.toJson(obj));

        } catch (Exception e) {

            System.out.println("Erro na servlet ao listar os times" + e.getStackTrace());

        } finally {
            out.close();
        }

    }

    public void sortearBB(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Time> obj = new ArrayList<Time>();

        Gson objJson = new Gson();

        try {
            TimeDAO timeDAO = new TimeDAO();

            obj = timeDAO.sortearCorpoB();

            out.print(objJson.toJson(obj));

        } catch (Exception e) {

            System.out.println("Erro na servlet ao listar os times" + e.getStackTrace());

        } finally {
            out.close();
        }

    }

    public void gravarChave(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Object> arrobj = new ArrayList<Object>();
        Gson objJson = new Gson();

        try {
            Time time = new Time();
            TimeDAO timeDAO = new TimeDAO();
            System.out.println(request.getParameter("id") + " time está na chave " + request.getParameter("id_chave"));

            time.setId_chave(Integer.parseInt(request.getParameter("id_chave")));
            time.setId_time(Integer.parseInt(request.getParameter("id")));

            timeDAO.setIdChave(time);

            out.print(objJson.toJson(arrobj));

        } catch (Exception e) {

            //perceba que a mensagem é gerada na controladora
            System.out.println("Erro ao alterar o time " + e.getMessage());

            out.print(objJson.toJson(arrobj));

        } finally {
            out.close();
        }

    }

    public void abastecerJogos(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        TimeJogoDAO timeJogoDAO = new TimeJogoDAO();
        ArrayList<Object> arrobj = new ArrayList<Object>();
        Gson objJson = new Gson();

        try {

            timeJogoDAO.abastecerTimeJogo();
            out.print(objJson.toJson(arrobj));

        } catch (Exception e) {

            System.out.println("Erro ao gravar jogos" + e.getMessage());

            out.print(objJson.toJson(arrobj));

        } finally {
            out.close();
        }

    }

    public void limparJogos(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        TimeJogoDAO timeJogoDAO = new TimeJogoDAO();
        ArrayList<Object> arrobj = new ArrayList<Object>();
        Gson objJson = new Gson();

        try {

            timeJogoDAO.limparTimeJogo();
            out.print(objJson.toJson(arrobj));

        } catch (Exception e) {

            System.out.println("Erro ao gravar jogos" + e.getMessage());

            out.print(objJson.toJson(arrobj));

        } finally {
            out.close();
        }

    }

    public void listarPorCategoria(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Time> obj = new ArrayList<Time>();

        Gson objJson = new Gson();

        try {
            TimeDAO timeDAO = new TimeDAO();
            System.out.println("A categoria é:" + request.getParameter("categoria"));
            obj = timeDAO.buscarPorSerie(request.getParameter("categoria"));
            System.out.println(obj.get(1).getNome_time());
            out.print(objJson.toJson(obj));

        } catch (Exception e) {

            System.out.println("Erro na servlet ao listar os times" + e.getStackTrace());

        } finally {
            out.close();
        }

    }

    public void alterarDivisao(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Object> arrobj = new ArrayList<Object>();
        Gson objJson = new Gson();

        try {

            Time time = new Time();
            TimeDAO timeDAO = new TimeDAO();
            System.out.println(request.getParameter("id"));

            time.setId_time(Integer.parseInt(request.getParameter("id")));
            time.setCategoria(request.getParameter("categoria"));
            time.setCabeca(Integer.parseInt(request.getParameter("cabeca")));

            timeDAO.atualizarDivisao(time);

            out.print(objJson.toJson(arrobj));

        } catch (Exception e) {

            //perceba que a mensagem é gerada na controladora
            System.out.println("Erro ao alterar o time " + e.getMessage());

            out.print(objJson.toJson(arrobj));

        } finally {
            out.close();
        }

    }

    public void alterarPagamento(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Object> arrobj = new ArrayList<Object>();
        Gson objJson = new Gson();

        try {

            Time time = new Time();
            TimeDAO timeDAO = new TimeDAO();

            time.setId_time(Integer.parseInt(request.getParameter("id")));
            time.setStatus(Integer.parseInt(request.getParameter("status")));

            timeDAO.atualizarPagamento(time);

            out.print(objJson.toJson(arrobj));

        } catch (Exception e) {

            //perceba que a mensagem é gerada na controladora
            System.out.println("Erro ao alterar o time " + e.getMessage());

            out.print(objJson.toJson(arrobj));

        } finally {
            out.close();
        }

    }

    public void timesA(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Time> obj = new ArrayList<Time>();

        Gson objJson = new Gson();

        try {
            TimeDAO timeDAO = new TimeDAO();

            obj = timeDAO.buscarTimesA();

            out.print(objJson.toJson(obj));

        } catch (Exception e) {

            System.out.println("Erro na servlet ao listar os times" + e.getStackTrace());

        } finally {
            out.close();
        }

    }

    public void timesB(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        ArrayList<Time> obj = new ArrayList<Time>();

        Gson objJson = new Gson();

        try {
            TimeDAO timeDAO = new TimeDAO();

            obj = timeDAO.buscarTimesB();

            out.print(objJson.toJson(obj));

        } catch (Exception e) {

            System.out.println("Erro na servlet ao listar os times" + e.getStackTrace());

        } finally {
            out.close();
        }

    }

    public void validarDivisao(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        Gson objJson = new Gson();

        try {
            TimeDAO timeDAO = new TimeDAO();
            int aAtivos;
            int aCabeca;
            int bAtivos;
            int bCabeca;
            String txt = "Validação realizada ! ";

            aAtivos = timeDAO.contarTimesAAtivos();
            aCabeca = timeDAO.contarCabecaTimesA();
            bAtivos = timeDAO.contarTimesBAtivos();
            bCabeca = timeDAO.contarCabecaTimesB();

            //realizando testes quantidade de times cat A
            if (aAtivos == 18) {
                txt = txt + " Quantidade de times na categoria A está CORRETA !";

            } else if (aAtivos > 18) {
                int aux1 = 0;
                aux1 = aAtivos - 18;
                txt = txt + " Está sobrando " + aux1 + " times na categoria A";
            } else {
                int aux1 = 0;
                aux1 = 18 - aAtivos;
                txt = txt + " Está faltando " + aux1 + " times na categoria A";

            }
            //realizando testes quantidade cabeças de chave cat A

            if (aCabeca == 6) {

                txt = txt + ", Quantidade de cabeças de chave na categoria A está CORRETA !";
            } else if (aCabeca > 6) {
                int aux2 = 0;
                aux2 = aCabeca - 6;
                txt = txt + ", Está sobrando " + aux2 + " cabeças de chave na categoria A";

            } else {

                int aux2 = 0;
                aux2 = 6 - aCabeca;
                txt = txt + ", Está faltando " + aux2 + " cabeças de chave na categoria A";

            }

            //realizando testes quantidade de times cat B
            if (bAtivos == 18) {
                txt = txt + " Quantidade de times na categoria B está CORRETA !";

            } else if (bAtivos > 18) {
                int aux1 = 0;
                aux1 = bAtivos - 18;
                txt = txt + " Está sobrando " + aux1 + " times na categoria B";
            } else {
                int aux1 = 0;
                aux1 = 18 - bAtivos;
                txt = txt + " Está faltando " + aux1 + " times na categoria B";

            }
            //realizando testes quantidade cabeças de chave cat B

            if (bCabeca == 6) {

                txt = txt + ", Quantidade de cabeças de chave na categoria A está CORRETA !";
            } else if (bCabeca > 6) {
                int aux2 = 0;
                aux2 = bCabeca - 6;
                txt = txt + ", Está sobrando " + aux2 + " cabeças de chave na categoria B";

            } else {

                int aux2 = 0;
                aux2 = 6 - bCabeca;
                txt = txt + ", Está faltando " + aux2 + " cabeças de chave na categoria B";

            }

            out.print(objJson.toJson(txt));

        } catch (Exception e) {

            System.out.println("Erro na servlet ao listar os times" + e.getStackTrace());

        } finally {
            out.close();
        }

    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int oper = Integer.parseInt(request.getParameter("oper"));
        try {
            switch (oper) {

                case 1:
                    cadastrar(request, response);
                    break;

                case 2:
                    listar(request, response);
                    break;

                case 3:
                    alterar(request, response);
                    break;

                case 4:
                    ativo(request, response);
                    break;

                case 5:
                    apagar(request, response);
                    break;

                case 6:
                    inativo(request, response);
                    break;

                case 7:
                    sortearHA(request, response);
                    break;

                case 8:
                    sortearBA(request, response);
                    break;

                case 9:
                    sortearHB(request, response);
                    break;

                case 10:
                    sortearBB(request, response);
                    break;
                case 11:
                    gravarChave(request, response);
                    break;
                case 12:
                    abastecerJogos(request, response);
                    break;

                case 13:
                    limparJogos(request, response);
                    break;
                case 14:
                    listarPorCategoria(request, response);
                    break;

                case 15:
                    timesA(request, response);
                    break;
                case 16:
                    timesB(request, response);
                    break;

                case 17:
                    alterarDivisao(request, response);
                    break;

                case 18:
                    alterarPagamento(request, response);
                    break;

                case 19:
                    validarDivisao(request, response);
                    break;

            }

        } catch (Exception e) {
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold> 
}
